package com.cy.cur;

import java.util.concurrent.atomic.AtomicInteger;


// ABA 问题
public class CasDemo_ABA_1 {

    public static AtomicInteger a = new AtomicInteger(1);

    public static void main(String[] args) {
        System.out.println("操作线程:" + Thread.currentThread().getName() + ",初始值:" + a.get());
        new Thread(new Runnable() {
            @Override
            public void run() {
                int expectNum = a.get();
                int newNum = expectNum + 1;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                boolean b = a.compareAndSet(expectNum, newNum);
                System.out.println("操作线程:" + Thread.currentThread().getName() + ",CAS结果:" + b);
            }
        }, "主线程").start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                // 保证main 先执行
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                a.incrementAndGet();
                System.out.println("干扰线程:" + Thread.currentThread().getName() + ",[incr]值结果:" + a.get());
                a.decrementAndGet();
                System.out.println("干扰线程:" + Thread.currentThread().getName() + ",[decr]值结果:" + a.get());
            }
        }, "干扰线程").start();

    }


}
